import React, {Component} from 'react';
import {Breadcrumb, message, Form, Input, Button, Select, Modal, Table, Space, InputNumber} from "antd";
import {NavLink} from "react-router-dom";
import {connect} from "react-redux";
import imgUrl from "../../assets/img/noinfo.png";

const {Option} = Select;

@connect(state => ({userInfo: state.userInfo}))
class User extends Component {
    state = {
        changepassword: {}, //修改密码弹窗数据
        changerealstateuser: {}, //正在审核的用户信息
        changecompanystateuser: {}, //公司认证信息
        dialogstudent: false,
        dialogcompany: false,
        dialogpw: false, //密码框
        loading:false,
        pagelistquery: {
            realstate: "",
            companystate: "",
            total: 0,
            page: 1,
            pagesize: 10,
            user: "",

        },
        tableData: [], //列表信息
        activationttime: {
            time: 0,
            userid: "",
            jubao_id: "",
            dialog: false //密码框
        }
    }
    userStateFilter = (state) => {
        if (state === 3) {
            return "认证成功";
        }
        if (state === 2) {
            return "待审核";
        }
        if (state === 1) {
            return "未认证";
        }
        if (state === 0) {
            return "认证失败";
        }
    }
    activationDate = (row) => {
        let activationttime = this.state.activationttime;
        activationttime.userid = row.user_id;
        activationttime.dialog = true;
        this.setState({activationttime: activationttime});
    }
    //修改账号封禁时间
    changeActivationDate = async () => {
        let changepassword = this.state.changepassword;
        changepassword.type = "adminuser";
        this.setState({changepassword: changepassword});
        let result = await this.$axios.post("/admin/changeactivationdate", this.state.activationttime);
        if (result.data.state.type === "SUCCESS") {
            message.success("操作成功");
            let activationttime = this.state.activationttime
            activationttime.dialog = false;
            this.setState({activationttime: activationttime});
            this.getUserList();
        }
    }
    changeState = async (type, state, userid, companyname) => {
        let data = {
            type: type,
            state: state,
            user_id: userid,
            company_name: companyname
        };
        let result = await this.$axios.post("/admin/changeuserstate", data);
        if (result.data.state.type === "SUCCESS") {
            message.success("操作成功成功");
            this.setState({dialogstudent: false, dialogcompany: false});
            this.getUserList();
        }
    }
    changePw = (row) => {
        let row1 = JSON.parse(JSON.stringify(row))
        this.setState({dialogpw: true, changepassword: row1});
    }
    //修改密码
    changePassword = async () => {
        let changepassword = this.state.changepassword;
        changepassword.type = "adminuser";
        this.setState({changepassword: changepassword});
        let result = await this.$axios.post("/admin/changepassword", this.state.changepassword);
        if (result.data.state.type === "SUCCESS") {
            message.success("修改成功");
            this.setState({dialogpw: false, changepassword: {}});
            this.refs.editPW.resetFields()
        }
    }
    deleteUser = async (row) => {
        let data = {
            user_id: row.user_id,
            usertype: "user"
        };
        let result = await this.$axios.post("/admin/deleteuser", data);
        if (result.data.state.type === "SUCCESS") {
            message.success("删除成功");
            this.getUserList();
        }
    }
    changeRealStateDialog = (user) => {
        let changerealstateuser = JSON.stringify(user);
        changerealstateuser = JSON.parse(changerealstateuser);
        changerealstateuser.studentcard = JSON.parse(changerealstateuser.studentcard);
        this.setState({changerealstateuser: changerealstateuser, dialogstudent: true});
    }
    changeCompanyStateDialog = (user) => {
        let changecompanystateuser = JSON.stringify(user);
        changecompanystateuser = JSON.parse(changecompanystateuser);
        changecompanystateuser.companyimg = JSON.parse(changecompanystateuser.companyimg);
        this.setState({changecompanystateuser: changecompanystateuser, dialogcompany: true});
    }
    handleSizeChange = (current, size) => {
        let pagelistquery = this.state.pagelistquery
        pagelistquery.pagesize = size;
        this.setState({pagelistquery: pagelistquery});
        this.getUserList();
    }
    handleCurrentChange = (page, pagesize) => {
        let pagelistquery = this.state.pagelistquery;
        pagelistquery.page = page;
        pagelistquery.pagesize = pagesize;
        this.setState({pagelistquery: pagelistquery});
        this.getUserList();
    }
    getUserList = async (values) => {
        this.setState({loading:true});
        values = {...this.state.pagelistquery, ...values};
        this.setState({pagelistquery: values});
        let result = await this.$axios.post("/admin/getuserlist", values);
        if (result.data.state.type === "SUCCESS") {
            let pagelistquery = this.state.pagelistquery;
            pagelistquery.total = result.data.count;
            this.setState({tableData: result.data.data, pagelistquery: pagelistquery});
            this.setState({loading:false});
        }
    }
    jubao = () => {
        let pagelistquery = this.state.pagelistquery;
        pagelistquery.user = this.props.location.state.user;
        let activationttime = this.state.activationttime;
        activationttime.jubao_id = this.props.location.state.jubao_id;
        this.setState({pagelistquery: pagelistquery, activationttime: activationttime});
    }
    getPassword = (values) => {
        let changepassword = this.state.changepassword;
        if(values.newpassword){
            changepassword.newpassword = values.newpassword;
            this.setState({changepassword: changepassword});
            this.changePassword();
        }
        else message.error("密码不能为空")
    }
    getBanTime = (values) => {
        let activationttime = this.state.activationttime;
        activationttime.time = values.time;
        this.setState({activationttime: activationttime});
        this.changeActivationDate();
    }
    remove = () => {
        let activationttime =this.state.activationttime;
        activationttime.dialog = false;
        this.setState({activationttime: activationttime});
    }
    componentDidMount() {
        if (this.props.location.state) {
            this.jubao();
        }
        this.getUserList();
    }

    render() {
        let {
            tableData, dialogpw, activationttime,
            changerealstateuser, changepassword,loading,
            dialogcompany,changecompanystateuser,dialogstudent
        } = this.state;
        tableData.map((item, index) => {
            return item.key = index;
        })
        const columns = [
            {
                title: "账号",
                dataIndex: "username"
            },
            {
                title: "昵称",
                dataIndex: "nickname"
            },
            {
                title: "实名认证状态",
                dataIndex: "realstate",
                render: (text, record) => (<Button type="text" style={{color: "#409EFF"}}
                                                   onClick={() => this.changeRealStateDialog(record)}
                >{this.userStateFilter(text)}</Button>)
            },
            {
                title: "公司认证状态",
                dataIndex: "companystate",
                render: (text, record) => (<Button type="text" style={{color: "#409EFF"}}
                                                   onClick={() => this.changeCompanyStateDialog(record)}
                >{this.userStateFilter(text)}</Button>)
            },
            {
                title: "启用时间",
                dataIndex: "activationdate",
                render: text => <span>{this.dateFormat(text)}</span>
            },
            {
                title: "操作",
                dataIndex: "user_id",
                render: (text, record) => (
                    <Space size="small">
                        <Button type="text" style={{color: "#409EFF"}} size={"small"} onClick={() => {
                            this.activationDate(record)
                        }}
                                disabled={this.props.userInfo.uinfo.jurisdiction.isyh !== '1' && this.props.userInfo.uinfo.username !== 'admin'}
                        >封禁解除</Button>
                        <Button type="text" style={{color: "#409EFF"}} size={"small"} onClick={() => {
                            this.deleteUser(record)
                        }}
                                disabled={this.props.userInfo.uinfo.jurisdiction.issh !== '1' && this.props.userInfo.uinfo.username !== 'admin'}
                        >删除</Button>
                        <Button type="text" style={{color: "#409EFF"}} size={"small"} onClick={() => {
                            this.changePw(record)
                        }}>修改密码</Button>
                    </Space>
                )
            },
        ]
        return (
            <div>
                <div className="top">
                    <Breadcrumb>
                        <Breadcrumb.Item>
                            <NavLink to='/'>首页</NavLink>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>
                            用户管理
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>
                            普通用户管理
                        </Breadcrumb.Item>
                    </Breadcrumb>
                </div>
                <div className="main">
                    <div>
                        <Form onFinish={this.getUserList} layout={"inline"}>
                            <Form.Item name="user" initialValue=""
                                       style={{width: '15%', margin: "15px 10px 22px 0"}}>
                                <Input placeholder="账号查找"></Input>
                            </Form.Item>
                            <Form.Item name="realstate" label="学生" initialValue=""
                                       style={{width: '20%', margin: "15px 10px 22px 0"}}>
                                <Select placeholder="状态">
                                    <Option value="">全部</Option>
                                    <Option value="1">未认证</Option>
                                    <Option value="2">待认证</Option>
                                    <Option value="3">认证通过</Option>
                                    <Option value="-1">认证失败</Option>
                                </Select>
                            </Form.Item>
                            <Form.Item name="companystate" label="公司" initialValue=""
                                       style={{width: '20%', margin: "15px 10px 22px 0"}}>
                                <Select placeholder="模块">
                                    <Option value="">全部</Option>
                                    <Option value="1">未认证</Option>
                                    <Option value="2">待认证</Option>
                                    <Option value="3">认证通过</Option>
                                    <Option value="-1">认证失败</Option>
                                </Select>
                            </Form.Item>
                            <Form.Item style={{margin: "15px 10px 22px 0"}}>
                                <Button type="primary" htmlType="submit">查询</Button>
                            </Form.Item>
                        </Form>
                    </div>
                    <Table dataSource={tableData}
                           columns={columns} bordered
                           loading={loading}
                           pagination={{
                               total: this.state.pagelistquery.total,
                               showSizeChanger: true,
                               showQuickJumper: true,
                               onChange: this.handleCurrentChange,
                               onShowSizeChange: this.handleSizeChange,
                               showTotal: total => `共 ${total} 条`,
                               position: ["bottomLeft"]
                           }}
                    ></Table>
                    {/*密码框*/}
                    <Modal visible={dialogpw} title="输入新的密码"
                           onCancel={() => this.setState({dialogpw: false})}
                           footer={false}
                    >
                        <Form onFinish={this.getPassword} labelCol={{span: 4}} ref={"editPW"}>
                            <Form.Item label="账号：">
                                {changepassword.username}
                            </Form.Item>
                            <Form.Item name="newpassword" initialValue={changepassword.newpassword} label="新密码:">
                                <Input/>
                            </Form.Item>
                            <Form.Item>
                                <Space style={{float:"right"}}>
                                    <Button onClick={() => this.setState({dialogpw: false})}>
                                        取消
                                    </Button>
                                    <Button type="primary" htmlType="submit">
                                        确定
                                    </Button>
                                </Space>
                            </Form.Item>
                        </Form>
                    </Modal>
                    {/*用户信息认证*/}
                    <Modal visible={dialogstudent} title="学生认证"
                           onCancel={() => this.setState({dialogstudent: false})}
                           footer={[
                               (
                                   (changerealstateuser.realstate!==1 && changerealstateuser.realstate!==3)?
                                       <Button key="pass" type="primary"
                                               onClick={()=>this.changeState('realstate',3,changerealstateuser.user_id)}>
                                           通过认证
                                       </Button>:null
                               ),
                               (
                                   (changerealstateuser.realstate!==1 && changerealstateuser.realstate!==0)?
                                       <Button key="fail" type="danger"
                                               onClick={()=>this.changeState('realstate',0,changerealstateuser.user_id)}>
                                           不通过认证
                                       </Button>:null
                               ),
                               <Button key="back" onClick={()=>this.setState({dialogstudent:false})}>
                                   取消
                               </Button>,
                           ]}
                    >
                        {
                            changerealstateuser.realstate===1?
                                <div>
                                    <img src={imgUrl} alt={"图片缺失"} width={"100%"}/>
                                    <div style={{width:'100%',textAlign:'center'}}>该用户还没有添加认证信息</div>
                                </div>:
                                <Form>
                                    <Form.Item label="学号：">
                                        <Form.Item>{changerealstateuser.realname}</Form.Item>
                                    </Form.Item>
                                    <Form.Item label="姓名:">
                                        <Form.Item>{changerealstateuser.studentid}</Form.Item>
                                    </Form.Item>
                                    <Form.Item label="学生证:">
                                        <Form.Item>
                                            {
                                                changerealstateuser.studentcard?
                                                    changerealstateuser.studentcard.map((img,id)=>
                                                    <img key={id} src={img.url} alt={"图片缺失"} style={{width:'40%',margin:'20px'}}/>
                                                    ):null
                                            }
                                        </Form.Item>
                                    </Form.Item>
                                </Form>
                        }
                    </Modal>
                    <Modal visible={activationttime.dialog} title="封禁时间（天）"
                           onCancel={this.remove}
                           footer={false}
                    >
                        <Form onFinish={this.getBanTime}>
                            <Form.Item>
                                <Form.Item name="time" initialValue={0}>
                                    <InputNumber/>
                                </Form.Item>
                            </Form.Item>
                            <Form.Item>
                                <Space style={{float:"right"}}>
                                    <Button type="primary" htmlType="submit">
                                        确定
                                    </Button>
                                    <Button onClick={this.remove}>
                                        取消
                                    </Button>
                                </Space>
                            </Form.Item>
                        </Form>
                    </Modal>
                    {/*公司信息认证*/}
                    <Modal visible={dialogcompany} title="公司认证"
                           onCancel={() => this.setState({dialogcompany: false})}
                           footer={[
                               (
                                   (changecompanystateuser.companystate!==1 && changecompanystateuser.companystate!==3)?
                                       <Button key="pass" type="primary"
                                               onClick={()=>this.changeState('companystate',3,changecompanystateuser.user_id,changecompanystateuser.companyname)}>
                                           通过认证
                                       </Button>:null
                               ),
                               (
                                   (changecompanystateuser.companystate!==1 && changecompanystateuser.companystate!==0)?
                                       <Button key="fail" type="danger"
                                               onClick={()=>this.changeState('companystate',0,changecompanystateuser.user_id)}>
                                           不通过认证
                                       </Button>:null
                               ),
                               <Button key="back" onClick={()=>this.setState({dialogcompany:false})}>
                                   取消
                               </Button>,
                           ]}
                    >
                        {
                            changecompanystateuser.companystate===1?
                                <div>
                                    <img src={imgUrl} alt={"图片缺失"} width={"100%"}/>
                                    <div style={{width:'100%',textAlign:'center'}}>该用户还没有添加公司认证信息</div>
                                </div>:
                                <Form>
                                    <Form.Item label="公司名称：">
                                        <Form.Item>{changecompanystateuser.companyname}</Form.Item>
                                    </Form.Item>
                                    <Form.Item label="相关信息图片:">
                                        <Form.Item>
                                            {
                                                changecompanystateuser.companyimg?
                                                    changecompanystateuser.companyimg.map((img,id)=>
                                                        <img key={id} src={img.url} alt={"图片缺失"} style={{width:'40%',margin:'20px'}}/>
                                                    ):null
                                            }
                                        </Form.Item>
                                    </Form.Item>
                                </Form>
                        }
                    </Modal>
                </div>
            </div>
        );
    }
}

export default User;
